const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const db = require('../untils/database')
const jwt = require('jsonwebtoken')
// const { resolve, reject } = require('core-js/fn/promise')

const dynamic = new Router()

dynamic.use(bodyParser());

dynamic.post('/add',async(ctx)=>{
    console.log(ctx.request.body);
    let userName = ctx.request.body.userName
    let userID = ctx.request.body.userID
    let content = ctx.request.body.content
    let status = ctx.request.body.status
    let sql =`INSERT INTO dynamic (user_name, user_id, dynamic_content, status) values ('${userName}', '${userID}', '${content}', '${status}')`
    let result = await new Promise((resolve,reject)=>{
        return db.query(sql,(err,data)=>{
            if(err) throw err;
            let obj = {
                // data:result,
                msg: 'success',
            }
            resolve(obj)
        })   
    })
    if(result){
        ctx.body = result
    }
})
        
dynamic.post('/page',async(ctx)=>{
    let pageSize =  5 //每页显示数量
    let start = ctx.request.body.pageNum ? ((ctx.request.body.pageNum-1)*pageSize) : 0
    // console.log(ctx.request.body);
    let userId = ctx.request.body.userId
    let sql
    if(userId){
        sql = `SELECT * FROM dynamic WHERE status=0 or user_id='${userId}' order by createTime desc limit ${start},${pageSize}`;
    }else{
        sql = `SELECT * FROM dynamic WHERE status=0 order by createTime desc limit ${start},${pageSize}`;
    }
    let result = await new Promise((resolve,reject)=>{
        return db.query(sql,(err,data)=>{
            if(err) throw err;
            if(data.length>0){
                resolve(data)
            }else{
                resolve(false)
            }
        })   
    })
    if(result){
        ctx.body = {
            message: result,
            msg: 'success'
        }
    }else{
        ctx.body = {
            data: null,
            msg: 'successs'
        }
    }
})

dynamic.delete('/deleteDynamic',async(ctx)=>{
    let id = ctx.request.body.id 
    let sql = `DELETE FROM dynamic WHERE id =${id}`;
    let result = await new Promise((resolve,reject)=>{
        return db.query(sql,(err,data)=>{
            if(err) throw err;
            let obj = {
                data,
                msg: 'success',
            }
            resolve(obj)
        })   
    })
    if(result){
        ctx.body = result
    }
})

module.exports = dynamic;